//
// Created by chizuru on 2025/9/2.
//

#include "Invoker.h"
using std::vector;
using std::cerr;
using std::unique_ptr;

OperationResult camera_link_bobcat::Invoker::executeWithRollback(std::vector<std::unique_ptr<camera_link_bobcat::ICommand>> &cmds) {
    vector<ICommand*> executed;
    for (auto &cptr : cmds) {
        bool ok = cptr->execute();
        if (!ok) {
            // undo in reverse
            for (auto it = executed.rbegin(); it != executed.rend(); ++it) {
                try {
                    auto r = (*it)->undo();
                    if (!r) {
                        return {false, ErrorCode::RollbackFailure, "Rollback failed"};
                    }
                } catch(...) {
                    return {false, ErrorCode::RollbackFailure, "Rollback failed"};
                }
            }
            return {false, ErrorCode::CommandFailure, "Command execution failed, rollback successful"};
        }
        executed.push_back(cptr.get());
    }
    return {true, ErrorCode::OK, "Command execution successful"};
}